package com.mzj.saas.mservice.property.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.Joiner;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.entity.CommunityBuild;
import com.mzj.saas.mservice.community.entity.CommunityBuildUnit;
import com.mzj.saas.mservice.community.repository.CommunityBuildRepository;
import com.mzj.saas.mservice.community.repository.CommunityBuildUnitRepository;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.property.common.ComplainSuggestEnum;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.entity.ComplainSuggest;
import com.mzj.saas.mservice.property.entity.ComplainSuggestImg;
import com.mzj.saas.mservice.property.entity.EstateRepairsRecord;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.property.repository.ComplainSuggestImgRepository;
import com.mzj.saas.mservice.property.repository.ComplainSuggestReplyRepository;
import com.mzj.saas.mservice.property.repository.ComplainSuggestRepository;
import com.mzj.saas.mservice.property.vo.ComplainSuggestApiData;
import com.mzj.saas.mservice.property.vo.ComplainSuggestVO;
import com.mzj.saas.mservice.property.vo.EstateRepairsRecordVO;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ComplainSuggestService {
    private static final Logger log = LoggerFactory.getLogger(ComplainSuggestService.class);

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private ComplainSuggestRepository complainSuggestRepository;
    @Autowired
    private ComplainSuggestImgService complainSuggestImgService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private ComplainSuggestImgRepository complainSuggestImgRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private CommunityBuildRepository communityBuildRepository;
    @Autowired
    private CommunityBuildUnitRepository communityBuildUnitRepository;
    @Autowired
    private AppCommunityService appCommunityService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private ComplainSuggestReplyRepository complainSuggestReplyRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    /**
     * 新增投诉建议
     *
     * @param accessToken
     * @param complainSuggestVO
     * @return
     */
    public ResultBean<ComplainSuggestVO> save(String accessToken, ComplainSuggestVO complainSuggestVO) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) return ResultBean.failedResultOfToken();

            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(token.getId(), token.getId());
            if (user == null) {
                return ResultBean.failedResultWithMsg("用户不存在");
            }

            if (StrUtil.isEmpty(complainSuggestVO.getContent())) {
                return ResultBean.failedResultOfParamWithMsg("请输入内容");
            }
            if (complainSuggestVO.getType() == null) {
                return ResultBean.failedResultOfParamWithMsg("类型为空");
            }
            if (ComplainSuggestEnum.getTypeName(complainSuggestVO.getType()) == null) {
                return ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10005);
            }
            if (complainSuggestVO.getContent() == null) {
                return ResultBean.failedResultOfParamWithMsg("内容为空");
            }
            if (StringUtils.isBlank(complainSuggestVO.getHouseId())) {
                return ResultBean.failedResultOfParamWithMsg("房屋id为空");
            }
            if (complainSuggestVO.getOrgId() == null) {
                return ResultBean.failedResultOfParamWithMsg("物业id为空");
            }
            //限制退租后用户不能提出投诉建议 xiaolong 20230410
            String houseId = complainSuggestVO.getHouseId();
            String mobile = token.getPhone();
            List<CommunityHouseUser> byCommunityHouseIdAndStatusAndMobile = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(houseId, 1, mobile);
            if (byCommunityHouseIdAndStatusAndMobile.isEmpty()) {
                return ResultBean.failedResultOfParamWithMsg("已退租无法提交投诉建议");
            }
            ComplainSuggest complainSuggest = new ComplainSuggest();
            complainSuggest.setType(complainSuggestVO.getType());
            complainSuggest.setContent(complainSuggestVO.getContent().getBytes("utf-8"));
            complainSuggest.setHouseId(complainSuggestVO.getHouseId());
            complainSuggest.setOrgId(complainSuggestVO.getOrgId());
            complainSuggest.setUserId(token.getId());
            complainSuggest.setUserName(user.getName());
            complainSuggest.setMobile(user.getPhone());
            complainSuggest.setCreateTime(new Date());
            complainSuggest.setStatus(0);
            complainSuggest.setOperatorId(token.getId());
            complainSuggest.setLastOperatorTime(new Date());
            complainSuggest.setAppUserId(token.getId());
            ComplainSuggest save = complainSuggestRepository.save(complainSuggest);

            /*//查用户关联房屋
            String sql = "SELECT u.house_id AS houseId ,h.`house_property_id` AS housePropertyId \n" +
                    "FROM saas_house_match_user u \n" +
                    "LEFT JOIN `saas_house` h ON u.house_id = h.`id`\n" +
                    "WHERE u.match_user_id = ? AND u.status = 1 AND h.`lease_status` = 1\n" +
                    "UNION \n" +
                    "SELECT u.house_id AS houseId ,h.`house_property_id` AS housePropertyId \n" +
                    "FROM saas_house_match_user u\n" +
                    "LEFT JOIN `saas_house` h ON u.house_id = h.`id` \n" +
                    "LEFT JOIN (SELECT c.apply_id, us.id, us.enterprise_user_id FROM saas_house_eligible_apply_cohabit c LEFT JOIN saas_app_user us ON us.card_number = c.card_number) c1 \n" +
                    "ON u.apply_id = c1.apply_id \n" +
                    "WHERE c1.id = ? OR c1.enterprise_user_id = ? AND u.status = 1 AND h.`lease_status` = 1\n" +
                    "UNION \n" +
                    "SELECT u2.community_house_id AS houseId ,h.`house_property_id` AS housePropertyId \n" +
                    "FROM saas_community_house_user u2\n" +
                    "LEFT JOIN `saas_house` h ON u2.community_house_id = h.`id`  \n" +
                    "WHERE u2.user_id = ? AND u2.status = 1";
            List<String> userIds = Arrays.asList(userId, userId, userId, userId);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, userIds.toArray());
            if (list.isEmpty()) {
                return ResultBean.failedResultWithMsg("无绑定物业，无法操作");
            }
            Map<String, Object> map = list.get(0);
            String housePropertyId = map.get("housePropertyId").toString();*/

            List<ComplainSuggestImg> complainSuggestImgList = complainSuggestVO.getComplainSuggestImgList();
            if (complainSuggestImgList != null && !complainSuggestImgList.isEmpty()) {
                for (ComplainSuggestImg complainSuggestImg : complainSuggestImgList) {
                    complainSuggestImg.setComplainSuggestId(save.getId());
                    complainSuggestImgService.save(complainSuggestImg);
                }
            }

            ComplainSuggestVO vo = convertToVO(save, token);

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 投诉建议列表
     *
     * @param accessToken
     * @param username    发起人
     * @param mobile      发起人电话
     * @param startTime   发起时间
     * @param endTime     结束时间
     * @param type        类型 1、建议 2、投诉
     * @param status      状态 1、待处理 2、已处理
     * @param pageNumber
     * @param pageSize    小区投诉建议
     */
    public ResultBean<ComplainSuggestApiData<ComplainSuggestVO>> listV2(String accessToken, String username, String mobile,
                                                                        String startTime, String endTime,
                                                                        Integer type, Integer status,
                                                                        String houseId,
                                                                        Integer pageNumber, Integer pageSize) {
        try {
            //校验登录信息
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) return ResultBean.failedResultOfToken();
            String userId = token.getId();
            mobile = token.getPhone();
            Long enterpriseId = token.getEnterpriseId();

            ComplainSuggestApiData<ComplainSuggestVO> apiData = new ComplainSuggestApiData<>();
            //判断用户是否已经被移除房屋，如果是，则不返回数据
            // CommunityHouseUser communityHouseUser = communityHouseUserRepository.findByUserIdAndMobileAndStatus(userId, mobile, 1);
            // if (communityHouseUser == null) {
            //     return ResultBean.failedResult(apiData);
            // }
            //投诉建议数据
            String querySql;
            //全部总数
            String countSql;
            //待处理数
            String pendingTotalSql;
            //已处理数
            String processedTotalSql;
            Map<String, Object> params = new HashMap<>();
            if (enterpriseId == null) {
                //投诉建议数据
                querySql = "SELECT cs.* ,h.residence_community_id as communityId, h.building_num as buildingNum,\n" +
                        " h.unit as unit, h.room_number as roomNumber FROM saas_complain_suggest cs" +
                        " LEFT JOIN saas_community_house_user chu ON cs.house_id = chu.community_house_id " +
                        " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                        "  WHERE cs.house_id = :houseId AND chu.status = 1 AND chu.mobile = :mobile AND chu.operator_time <= cs.create_time ";
                        // "  WHERE (cs.user_id = :userId AND chu.status = 1 AND chu.mobile = :mobile) ";
                //全部总数
                countSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " LEFT JOIN saas_community_house_user chu ON cs.house_id = chu.community_house_id" +
                        " WHERE cs.house_id = :houseId AND chu.status = 1 AND chu.mobile = :mobile AND chu.operator_time <= cs.create_time ";
                        // " WHERE (cs.user_id = :userId AND chu.status = 1 AND chu.mobile = :mobile) ";
                //待处理数
                pendingTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " LEFT JOIN saas_community_house_user chu ON cs.house_id = chu.community_house_id" +
                        " WHERE cs.house_id = :houseId AND chu.status = 1 AND chu.mobile = :mobile AND cs.status = 0 AND chu.operator_time <= cs.create_time ";
                        // " WHERE (cs.user_id = :userId AND chu.status = 1 AND chu.mobile = :mobile) AND cs.status = 0 ";
                //已处理数
                processedTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " LEFT JOIN saas_community_house_user chu ON cs.house_id = chu.community_house_id" +
                        " WHERE cs.house_id = :houseId AND chu.status = 1 AND chu.mobile = :mobile AND cs.status = 1 AND chu.operator_time <= cs.create_time ";
                        // " WHERE (cs.user_id = :userId AND chu.status = 1 AND chu.mobile = :mobile) AND cs.status = 1 ";
                // if (!StringUtils.isEmpty(mobile)) {
                //     params.put("mobile", mobile);
                //     querySql += " AND cs.mobile = :mobile ";
                //     countSql += " AND cs.mobile = :mobile ";
                //     pendingTotalSql += " AND cs.mobile = :mobile ";
                //     processedTotalSql += " AND cs.mobile = :mobile ";
                // }
                params.put("mobile", mobile);
                params.put("userId", userId);
                params.put("houseId", houseId);

            } else {
                //根据企业ID查询出用户层级权限
                DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                if (hierarchy == null) {
                    return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                }
                //获取企业用户ID
                Long id = hierarchy.getId();
                //根据企业用户ID获取公租房数据
                List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
                //获取企业标签集合
                List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签

                //判断是否是物业公司，如果不是直接返回null
                if (enterpriseTagIds.contains(4L)) {
                    //权限过滤
                    List<String> communityIds = null;
                    String collect = null;
                    List<Map<String, Object>> communityList = appCommunityService.findCommunity(accessToken).getResultData();
                    if (CollectionUtil.isNotEmpty(communityList)) {
                        communityIds = communityList.stream().map(map -> map.get("communityId")
                                .toString()).collect(Collectors.toList());
                        collect = communityIds.stream().map(code -> "'" + code + "'").collect(Collectors.joining(","));
                    }
                    //投诉建议数据
                /*querySql = "SELECT cs.*,h.residence_community_id as communityId, h.building_num as buildingNum,\n" +
                        " h.unit as unit, h.room_number as roomNumber FROM saas_complain_suggest cs " +
                        " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                        "  WHERE (cs.org_id = :orgId or cs.user_id = :userId) ";*/
                    querySql = "SELECT cs.*,h.residence_community_id as communityId, h.building_num as buildingNum,\n" +
                            " h.unit as unit, h.room_number as roomNumber FROM saas_complain_suggest cs " +
                            " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                            "  WHERE h.residence_community_id in (" + collect + ")";
                    //全部总数
              /*  countSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " WHERE (cs.org_id = :orgId or cs.user_id = :userId) ";*/
                    countSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                            " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                            " WHERE h.residence_community_id in (" + collect + ")";
                    //" WHERE h.residence_community_id in (" + String.join(",", communityIds) + ")";
                    //待处理数
          /*      pendingTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " WHERE (cs.org_id = :orgId or cs.user_id = :userId) AND cs.status = 0 ";*/
                    pendingTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                            " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                            " WHERE cs.status = 0 and h.residence_community_id in (" + collect + ")";
                    //已处理数
              /*  processedTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                        " WHERE (cs.org_id = :orgId or cs.user_id = :userId) AND cs.status = 1 ";*/
                    processedTotalSql = "SELECT COUNT(*) FROM saas_complain_suggest cs " +
                            " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                            " WHERE cs.status = 1 and  h.residence_community_id in (" + collect + ")";
                } else {
                    return ResultBean.successfulResult(null);
                }

            }


            params.put("limit", pageSize);
            params.put("offset", pageNumber * pageSize);
            params.put("offset", pageNumber * pageSize);
            //params.put("orgId", enterpriseId);
            //params.put("userId", userId);

            //条件筛选
            if (!StringUtils.isEmpty(username)) {
                //params.put("username", username);
                //querySql += " AND cs.user_name = :username ";
                //countSql += " AND cs.user_name = :username ";
                //pendingTotalSql += " AND cs.user_name = :username ";
                //processedTotalSql += " AND cs.user_name = :username ";
                querySql += " AND cs.user_name like '%" + username + "%'";
                countSql += " AND cs.user_name like '%" + username + "%'";
                pendingTotalSql += " AND cs.user_name like '%" + username + "%'";
                processedTotalSql += " AND cs.user_name like '%" + username + "%'";
            }


            if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                params.put("startTime", startTime);
                params.put("endTime", DateUtils.getAddDaysTime(endTime, DateUtils.FORMAT_DATE_8, 1));
                querySql += " AND cs.create_time >= :startTime AND cs.create_time < :endTime";
                countSql += " AND cs.create_time >= :startTime AND cs.create_time < :endTime";
                pendingTotalSql += " AND cs.create_time >= :startTime AND cs.create_time < :endTime";
                processedTotalSql += " AND cs.create_time >= :startTime AND cs.create_time < :endTime";
            }

            if (type != null) {
                params.put("type", type);
                querySql += " AND cs.type = :type ";
                countSql += " AND cs.type = :type ";
                pendingTotalSql += " AND cs.type = :type ";
                processedTotalSql += " AND cs.type = :type ";
            }

            if (status != null) {
                params.put("status", status);
                querySql += " AND cs.status = :status ";
                countSql += " AND cs.status = :status ";
            }

            if (houseId != null) {
                params.put("houseId", houseId);
                querySql += " AND cs.house_id = :houseId ";
                countSql += " AND cs.house_id = :houseId ";
                pendingTotalSql += " AND cs.house_id = :houseId ";
                processedTotalSql += " AND cs.house_id = :houseId ";
            }
            querySql += " order by cs.create_time desc ";
            querySql += " LIMIT :limit OFFSET :offset ";

            List<ComplainSuggest> complainSuggestList = namedParameterJdbcTemplate.query(querySql, params, new BeanPropertyRowMapper<>(ComplainSuggest.class));
            Long count = namedParameterJdbcTemplate.queryForObject(countSql, params, Long.class);
            Long pendingTotal = namedParameterJdbcTemplate.queryForObject(pendingTotalSql, params, Long.class);
            Long processedTotal = namedParameterJdbcTemplate.queryForObject(processedTotalSql, params, Long.class);

            //封装数据
            List<ComplainSuggestVO> voList = new ArrayList<>();
            for (ComplainSuggest complainSuggest : complainSuggestList) {
                ComplainSuggestVO vo = convertToVO(complainSuggest, token);
                voList.add(vo);
            }

            for (ComplainSuggestVO vo : voList) {
                //业主标识：0否 1是
                if (userId.equals(vo.getOperatorId())) {
                    vo.setOperatorFlag(1);
                } else {
                    vo.setOperatorFlag(0);
                }


                // 新增物业回复次数
                Integer provinceReplyNumber = complainSuggestReplyRepository.findCountByTypeAndCSId(1, vo.getId());
                vo.setProvinceReplyNumber(provinceReplyNumber);

                //物业标识：0否 1是
                //if (enterpriseId != null && vo.getOrgId() != null && enterpriseId.intValue() == vo.getOrgId()) {
                //    vo.setPropertyFlag(1);
                //} else {
                //    vo.setPropertyFlag(0);
                //}
                if (enterpriseId != null && vo.getOrgId() != null && enterpriseId != -1) {
                    vo.setPropertyFlag(1);
                } else {
                    vo.setPropertyFlag(0);
                }
            }

            // 查询小区名称
            List<String> communityIds = voList.stream().filter(vo -> vo.getCommunityId() != null).map(ComplainSuggestVO::getCommunityId).distinct().collect(Collectors.toList());
            if (!communityIds.isEmpty()) {
                Map<String, String> map = communityRepository.findByIdIn(communityIds).stream().collect(Collectors.toMap(Community::getId, Community::getName));
                if (!map.isEmpty()) {
                    voList.forEach(vo -> vo.setCommunityName(map.get(vo.getCommunityId())));
                }
            }
            // 查询楼栋名称
            List<Long> buildingIds = voList.stream().filter(vo -> vo.getBuildingNum() != null).map(ComplainSuggestVO::getBuildingNum).distinct().collect(Collectors.toList());
            if (!buildingIds.isEmpty()) {
                Map<Long, String> map = communityBuildRepository.findByIdIn(buildingIds).stream().filter(vo -> vo.getName() != null).collect(Collectors.toMap(CommunityBuild::getId, CommunityBuild::getName));
                if (!map.isEmpty()) {
                    voList.forEach(vo -> vo.setBuildingNumName(map.get(vo.getBuildingNum())));
                }
            }
            // 查询单元名称
            List<Long> unitIds = voList.stream().filter(vo -> vo.getUnit() != null).map(ComplainSuggestVO::getUnit).distinct().collect(Collectors.toList());
            if (!unitIds.isEmpty()) {
                Map<Long, String> map = communityBuildUnitRepository.findByIdIn(unitIds).stream().collect(Collectors.toMap(CommunityBuildUnit::getId, CommunityBuildUnit::getName));
                if (!map.isEmpty()) {
                    voList.forEach(vo -> vo.setUnitName(map.get(vo.getUnit())));
                }
            }

            apiData.setTotal(count);
            apiData.setPendingTotal(pendingTotal);
            apiData.setProcessedTotal(processedTotal);
            apiData.setData(voList);

            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 投诉建议数据处理
     *
     * @param complainSuggest
     * @param token
     * @return
     */
    private ComplainSuggestVO convertToVO(ComplainSuggest complainSuggest, TokenRedisVo token) {
        ComplainSuggestVO vo = new ComplainSuggestVO();
        vo.setId(complainSuggest.getId());
        vo.setType(complainSuggest.getType());
        vo.setTypeName(ComplainSuggestEnum.getTypeName(vo.getType()));
        try {
            vo.setContent(new String(complainSuggest.getContent(), "utf-8"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        vo.setHouseId(complainSuggest.getHouseId());
        vo.setUserId(complainSuggest.getUserId());
        vo.setUserName(complainSuggest.getUserName());
        vo.setMobile(complainSuggest.getMobile());
        vo.setCreateTime(complainSuggest.getCreateTime());
        vo.setStatus(complainSuggest.getStatus());
        vo.setStatusName(vo.getStatus() == 0 ? "待处理" : "已处理");
        vo.setOperatorId(complainSuggest.getOperatorId());
        vo.setLastOperatorTime(complainSuggest.getLastOperatorTime());
        vo.setOrgId(complainSuggest.getOrgId());

        vo.setCommunityId(complainSuggest.getCommunityId());
        vo.setBuildingNum(complainSuggest.getBuildingNum());
        vo.setUnit(complainSuggest.getUnit());
        vo.setRoomNumber(complainSuggest.getRoomNumber());
        String replyCountSql = "SELECT COUNT(*) FROM saas_complain_suggest_reply WHERE complain_suggest_id = ?";
        Integer replyCount = jdbcTemplate.queryForObject(replyCountSql, Integer.class, complainSuggest.getId());
        vo.setReplyCount(replyCount);

        String recoilStateSql = "SELECT COUNT(*) FROM saas_complain_suggest_reply WHERE recoil_state = 0 and complain_suggest_id = ?";
        Integer recoilStateCount = jdbcTemplate.queryForObject(recoilStateSql, Integer.class, complainSuggest.getId());
        if (recoilStateCount > 0) {
            vo.setRecoilState(0);
        } else {
            vo.setRecoilState(1);
        }

        List<ComplainSuggestImg> complainSuggestImgs = complainSuggestImgService.findByComplainSuggestId(complainSuggest.getId());
        vo.setComplainSuggestImgList(complainSuggestImgs);

        return vo;
    }

    /**
     * 投诉建议处理
     *
     * @param accessToken
     * @param id
     * @return
     */
    @Transactional
    public ResultBean<ComplainSuggestVO> solve(String accessToken, Long id) {
        try {

            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) return ResultBean.failedResultOfToken();

            //更新处理状态
            String sql = "UPDATE saas_complain_suggest SET status = 1, last_operator_time = ? WHERE id = ?";
            int result = jdbcTemplate.update(sql, new Date(), id);

            if (result == 1) {
                //处理成功
                ComplainSuggest complainSuggest = complainSuggestRepository.findById(id).orElse(null);
                if (complainSuggest != null) {
                    ComplainSuggestVO vo = convertToVO(complainSuggest, token);


                    // 新增消息推送
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(complainSuggest.getHouseId());
                    // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                    backlogItem.setType(BacklogItemTypeEnum.COMPLAIN_SUGGEST_DISPOSE.getValue());
                    backlogItem.setTitle("投诉建议已处理");
                    List<House> houseList = houseRepository.findByIdAndStatus(complainSuggest.getHouseId(), 1);
                    House house = houseList.get(0);
                    Optional<Community> community = communityRepository.findById(house.getResidenceCommunityId());
                    Optional<CommunityBuild> communityBuild = communityBuildRepository.findById(house.getBuildingNum());
                    Optional<CommunityBuildUnit> communityBuildUnit = communityBuildUnitRepository.findById(house.getUnit());
                    backlogItem.setContent(community.get().getName() + communityBuild.get().getName() + "栋" + communityBuildUnit.get().getName() + "单元" + house.getRoomNumber() + "号，投诉建议已处理完毕！" );
                    backlogItem.setBusinessStatus("待查看");
                    backlogItem.setHandleStatus(0);// 0未读/未处理
                    backlogItem.setOperatorId(complainSuggest.getOperatorId());
                    backlogItem.setCreateTime(new Date());
                    backlogItem.setMatchUserId(complainSuggest.getAppUserId());// 承租人

                    backlogItemRepository.save(backlogItem);


                    return ResultBean.successfulResult(vo);
                } else {
                    return ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10001);
                }
            } else {
                return ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10001);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除投诉建议数据
     *
     * @param accessToken
     * @param id
     * @return
     */
    @Transactional
    public ResultBean<Object> delete(String accessToken, Long id) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            //删除
            complainSuggestRepository.deleteById(id);
            complainSuggestImgRepository.deleteByComplainSuggestId(id);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 投诉建议詳情
     *
     * @param accessToken
     * @param id          投诉建议id
     * @return
     */
    public ResultBean<ComplainSuggestVO> selectComplainSuggestByid(String accessToken, Long id) {
        //校验登录信息
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }
        String userId = token.getId();
        Long enterpriseId = token.getEnterpriseId();
        Optional<ComplainSuggest> complainSuggest = complainSuggestRepository.findById(id);
        if (ObjectUtil.isNull(complainSuggest)) {
            return ResultBean.failedResultWithMsg("数据不存在");
        }
        ComplainSuggestVO complainSuggestVO = convertToVO(complainSuggest.get(), token);
        //业主标识：0否 1是
        if (userId.equals(complainSuggestVO.getOperatorId())) {
            complainSuggestVO.setOperatorFlag(1);
        } else {
            complainSuggestVO.setOperatorFlag(0);
        }

        //物业标识：0否 1是
        if (enterpriseId != null && complainSuggestVO.getOrgId() != null && enterpriseId != -1) {
            complainSuggestVO.setPropertyFlag(1);
        } else {
            complainSuggestVO.setPropertyFlag(0);
        }

        List<House> houseList = houseRepository.findByIdAndStatus(complainSuggest.get().getHouseId(), 1);
        if (CollectionUtil.isEmpty(houseList)) {
            return ResultBean.failedResultWithMsg("房屋数据不存在");
        }
        //房号
        complainSuggestVO.setRoomNumber(houseList.get(0).getRoomNumber());
        // 查询小区名称
        Optional<Community> community = communityRepository.findById(houseList.get(0).getResidenceCommunityId());
        complainSuggestVO.setCommunityName(community.get().getName());

        // 查询楼栋名称
        Optional<CommunityBuild> communityBuild = communityBuildRepository.findById(houseList.get(0).getBuildingNum());
        complainSuggestVO.setBuildingNumName(communityBuild.get().getName());

        // 查询单元名称
        Optional<CommunityBuildUnit> communityBuildUnit = communityBuildUnitRepository.findById(houseList.get(0).getUnit());
        complainSuggestVO.setUnitName(communityBuildUnit.get().getName());
        return ResultBean.successfulResult(complainSuggestVO);
    }


}
